<?php


namespace App\Http\Controllers;


use App\Models\Game;
use App\Models\Score;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class GameController extends BaseController
{
    public function addGame(Request $request){
        $only = $request->only(['title', 'description']);

        $validator = Validator::make($only, [
            'title' => 'required|min:3|max:60',
            'description' => 'required|min:0|max:60'
        ], []);

        if ($validator->fails()){
            return $this->returnInvalid($validator->errors()->getMessages());
        }

        //TODO slug生成
        $slug = md5($only['title']);

        if (Game::where('title', $only['title'])->first() != null){
            return $this->returnJson(["slug" => "Game title already exists"], self::INVALID, 'invalid');
        }

        Game::insert([
           'user_id' => $request->user->id,
           'slug' => $slug,
           'title' => $only['title'],
           'scoreCount' => 0,
           'created_at' => time(),
           'description' => $only['description'],
        ]);

        return $this->returnJson(['slug' => $slug], self::NEW_RESOURCES);
    }

    public function getGames(Request $request){
        $size = $request->input('size', 10);
        $sortBy = $request->input('sortBy', 'title');
        $sortDir = $request->input('sortDir', 'asc');

        switch ($sortBy){
            case 'popular':
                $sortBy = 'games.scoreCount';
                break;
            case 'uploaddate':
                $sortBy = 'games.created_at';
                break;
            default: $sortBy = 'games.title';
        }

        $games = Game::orderBy($sortBy, $sortDir == 'asc' ? 'asc' : 'desc')->paginate($size)->toArray();

        foreach ($games['data'] as $key => $game){
            $games['data'][$key]['uploadTimestamp'] = $game['created_at'];
            $games['data'][$key]['author'] = User::where('id', $game['user_id'])->value('username');
        }

        return $this->returnJson([
            'page' => $games['current_page'],
            'size' => $size,
            'totalElements' => $games['total'],
            'content' => $games['data'],
        ]);
    }

    public function gameInfo($slug){
        $game = Game::where('slug', $slug)->first();

        $game['gamePath'] = "/games/" . $game['slug'];
        $game['uploadTimestamp'] = $game['created_at'];
        $game['author'] = User::where('id', $game['user_id'])->value('username');

        return $this->returnJson($game);
    }

    //D 列出该用户创建的游戏
    public function getUserGame(Request $request){
        $user_id = $request->user->user->id;

        $games = Game::where('user_id', $user_id)->get();

        return $this->returnJson([
            'data' => $games
        ]);
    }

    public function updateGame(Request $request, $slug){
        $game = Game::where('slug', $slug);


        if ($game->where('user_id', $request->user->user->id)->first() == null){
            return $this->returnInvalid('The author is not you');
        }

        $title = $request->input('title');
        $description = $request->input('description');

        $update = [];
        if (!empty($title)) $update['title'] = $title;
        if (!empty($description)) $update['description'] = $description;

        $game->update($update);

        return $this->returnJson();
    }

    public function delGame(Request $request,$slug){
        $game = Game::where('slug', $slug);

        if ($game->where('user_id', $request->user->user->id)->first() == null){
            return $this->returnInvalid('The author is not you');
        }

        $game->delete();

        return $this->returnJson();
    }

}
